package com.doyens.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.domain.ThumbImageConfig;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {

    private static  final List<String> CONTET_TYPE = Arrays.asList("image/gif","image.jpeg");

    private static final Logger LOGGER = LoggerFactory.getLogger(UploadService.class);

    @Autowired
    private FastFileStorageClient storageClient;

    @Autowired
    private ThumbImageConfig thumbImageConfig;
    public String uploadService(MultipartFile file) {
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());

        //校验文件类型
        String originalFilename = file.getOriginalFilename();
        String contentType = file.getContentType();
        if (!CONTET_TYPE.contains(contentType)){
            LOGGER.info("文件类型不合法:{}",originalFilename);
        }
        //校验文件的内容
            if (bufferedImage == null){
                LOGGER.info("文件内容不合法:{}",originalFilename);
                return null;
            }
            //保存到服务器中
           // file.transferTo(new File("C:\\doyens\\image\\"+originalFilename));
            String ext = StringUtils.substringAfterLast(originalFilename, ".");
            StorePath storePath = this.storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);
            return "http://image.doyens.com/"+storePath.getFullPath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回url,进行回显..
        return null;
    }
}
